﻿using ETask.Api.Dtos;
using ETask.Api.Models;
using ETask.Api.Repositories;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using ETask.Api.Data;

namespace ETask.Api.Services
{
    public class PlatRegisterService : IPlatRegisterService
    {
        private readonly IUserRepository _userRepository;

        private readonly IConfiguration _config;

        public PlatRegisterService(IUserRepository userRepository, IConfiguration config)
        {
            _userRepository = userRepository;
            _config = config;
        }

        public async Task<ApiResponse> Register(PlatRegisterDto dto)
        {
            User user = await _userRepository.GetByAccount(dto.Account);
            if (user == null)
            {
                return ApiResponse.Fail(400, "账号不存在");
            }
            string md5Password = Md5Helper.Encrypt32(dto.Password);
            if (!md5Password.Equals(dto.Password))
            {
                return ApiResponse.Fail(400, "密码错误");
            }
            string jwtToken = GenerateJwtToken(user);
            return ApiResponse.Ok(jwtToken);
        }

        private string GenerateJwtToken(User userInfo)
        {
            var jwtSettings = _config.GetSection("Jwt");
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings["Key"]));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var issuer = jwtSettings["Issuer"];
            var audience = jwtSettings["Audience"];

            var claims = new[]
            {
                new Claim(ClaimTypes.NameIdentifier, userInfo.Id.ToString()),
                new Claim(ClaimTypes.Name, userInfo.Name),
                new Claim("account", userInfo.Account),
            };

            var token = new JwtSecurityToken(
                issuer: issuer,
                audience: audience,
                claims: claims,
                expires: DateTime.Now.AddMonths(1),
                signingCredentials: creds
            );

            return new JwtSecurityTokenHandler().WriteToken(token);
        }
    }
}
